package com.foosun.dao;


import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.foosun.entity.wechat.WxMessage;
import com.foosun.entity.wechat.WxUser;

/**
 * 消息管理
 * 2014-10-09
 */
@Component
public class WxMessageDao extends BaseDao<WxMessage>  {
	
	public void saveWxMess(WxMessage wm) {
		try {
			String sql="insert into es_wxmessage (fromuser,touser,msgtype,createtime,contents) values"
					+"('"+wm.getFromuser()+"','"+wm.getTouser()+"','"+wm.getMsgtype()+"',"+wm.getCreatetime()
					+",'"+wm.getContents()+"')";
			
			this.getJdbcTemplate().update(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public WxUser getWxUser(String openid) {
		try {
			String sql="select * from es_wxuser where openid= ?";		
			WxUser user = null;
			try {
				
				user = this.getJdbcTemplate().queryForObject(sql, new WxUserMapper(), new Object[]{openid});
				
			} catch (EmptyResultDataAccessException e) {user = null;}
			return user;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	protected class WxUserMapper implements RowMapper<WxUser> {  
		  
		  public WxUser mapRow(ResultSet rs, int rowNum) throws SQLException {  
			  WxUser wu = new WxUser();  
			  wu.setId(rs.getInt("id"));
			  wu.setOpenid(rs.getString("openid"));
			  return wu;
		  }  
	}
	
	/**
	 * 根据openid，关注时间来确定是否已添加过此关注者
	 * @param openid
	 * @param createtime
	 * @return
	 */
	public int getUserByOpenid(String openid,long createtime) {
		try {
			String sql = "select count(*) from es_wxuser where openid = ? and subscribe_time = ?";
			int count = 0;
			try{
				count = this.getJdbcTemplate().queryForInt(sql, new Object[]{openid, createtime});
			}catch(EmptyResultDataAccessException e){count = 0;}
			return count;
		} catch (Exception e) {
			e.printStackTrace();
			return 0 ;
		}
	}
	
	/**
	 * 保存关注者
	 * @param user
	 */
	public void saveUser(WxUser user) {
		try {
			String sql="insert into es_wxuser (nickname,openid,country,province,city,sex,headimg,subscribe_time,wxgroup_id) values (?,?,?,?,?,?,?,?,?)";
			this.getJdbcTemplate().update(sql, new Object[]{user.getNickname(), user.getOpenid(), user.getCountry(), user.getProvince(), user.getCity(), user.getSex(), user.getHeadimg(), user.getSubscribe_time(), user.getWxgroup_id()});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除关注者
	 * @param openid
	 */
	public void deleteUser(String openid) {
		try {
			String sql="delete from es_wxuser where openid=?";	
			this.getJdbcTemplate().update(sql, new Object[]{openid});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
